package two_shang.otherTest.ThreadPackage;

public class 信号灯法 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Actor(tv).start();
        new Audience(tv).start();
    }
}

class Actor extends Thread {
    TV tv;

    public Actor(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                tv.play("喜羊羊与灰太狼");
            } else {
                tv.play("国窖1573");
            }
        }
    }
}

class Audience extends Thread {
    TV tv;

    public Audience(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }

}

class TV {
    String show;
    //T 演员工作
    //F 观众工作
    boolean flag = true;

    public synchronized void play(String show) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("当前节目:" + show);
        this.show = show;
        this.notifyAll();
        this.flag = !this.flag;
    }


    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("观众正在收看:" + this.show);
        this.notifyAll();
        this.flag = !this.flag;
    }


}
